<?php


namespace app\api\controller;


use app\common\controller\Api;
use think\Cache;
use think\Loader;
use think\Request;
use yansongda\pay\Pay;
use app\api\service\Message as messageService;
use app\api\service\Accesstoken;


class BaseApi extends Api {

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $openid;
    protected $mid;

    //通过token获取openid和mid
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $token = $this->request->header('token');
        $accessTokenService = new Accesstoken();
        $this->openid = $accessTokenService::getMemberByToken($token)['openid'];
        $this->mid = $accessTokenService::getMemberByToken($token)['id'];
    }

    /**
     * 支付的配置文件
     * @param $action   回调地址的方法
     * @return array    支付配置数据
     */
    public function processConfig($action){
        $baseurl = $this->request->domain();
        $config = [
            'miniapp_id' => Config('wxpay.appid'), // 小程序 APPID
            'mch_id' => Config('wxpay.mch_id'),
            'key' => Config('wxpay.key'),
            'notify_url' => $baseurl.'/api/Payresult/'.$action,//支付回调url
            'cert_client' => './apiclient_cert.pem', // optional，退款等情况时用到(文件放在更目录下)
            'cert_key' => './apiclient_key.pem',// optional，退款等情况时用到
            'log' => [ // optional
                'file' => './logs/wechat.log',
                'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout' => 5.0,
                'connect_timeout' => 5.0,
            ],
        ];
        return $config;
    }

    /**
     * 统一下单
     * @param $action           回调方法
     * @param $money            订单金额
     * @param $ordersn          订单号
     * @param $openid           openid
     * @return \yansongda\supports\Collection   支付成功携带验签的数据,客户端使用该数据拉起支付页面
     */
    public function processPay($action,$preData,$body = '订单支付'){
        $total_fee = $preData['money'] * 100;
        $payData = [
            'out_trade_no' => $preData['ordersn'],
            'total_fee' => $total_fee, // **单位：分**
            'body' => $body,
            'openid' => $preData['openid'],
        ];

        $config = $this->processConfig($action);
        $pay = Pay::wechat($config)->miniapp($payData);
        return $pay;
    }
    
    /**
     * 发送模板消息
     *
     * @param $info       openid,form_id/prepay_id
     * @param $data       模板内容
     */
    public function sendTemplateMessage($info,$data){
        $messageServie = new messageService();
        $messageServie->sendMessage($info,$data);
    }

}